using Abp.Domain.Entities.Auditing;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Text;
using Yozeev.SystemConfig;

namespace Yozeev.Help
{
	public class CommonHelp
	{

		/// <summary>
		/// 根据机构用户关系插入机构id和创建人id，创建时间
		/// </summary>
		/// <typeparam name="T">实体泛型</typeparam>
		/// <param name="entity"></param>
		/// <param name="createBranch">机构用户关系</param>
		public static void SetBranchId<T>(T entity, BranchUser createBranch) where T : ByBranchEntity<Guid>
		{
			if (createBranch != null)
			{
				entity.BranchId = createBranch.BranchId;
				entity.CreatorUserId = createBranch.UserId;
			}
			entity.CreationTime = DateTime.Now;
		}
		/// <summary>
		/// 生成二维码
		/// </summary>
		/// <param name="qrCode"></param>
		/// <returns></returns>
		public static string getQRCode(string qrCode)
		{
			return qrCode.Replace("-", "");
		}
		#region 生成20位凭证码
		public static string getVoucherNo()
		{
			int min = 0; int max = 100000;
			Random r = new Random(Guid.NewGuid().GetHashCode());
			var temp = r.Next(min, max) + "";
			return DateToTimestampLong(DateTime.Now) + temp.PadLeft(6, '0');
		}
		/// <summary>
		/// 获取14位时间戳
		/// </summary>
		/// <param name="date"></param>
		/// <returns></returns>
		public static long DateToTimestampLong(DateTime date)
		{
			DateTime origin = new DateTime(1970, 1, 1, 8, 0, 0, 0);
			TimeSpan diff = date - origin;
			long timestamp = (long)Math.Floor(diff.TotalMilliseconds);
			return timestamp;
		}
		#endregion

		/// <summary>
		/// 获取枚举值上的Description特性的说明
		/// </summary>
		/// <typeparam name="T">枚举类型</typeparam>
		/// <param name="obj">枚举值</param>
		/// <returns>特性的说明</returns>
		public static string GetEnumDescription<T>(T obj)
		{
			var type = obj.GetType();
			FieldInfo field = type.GetField(Enum.GetName(type, obj));
			DescriptionAttribute descAttr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
			if (descAttr == null)
			{
				return string.Empty;
			}

			return descAttr.Description;
		}
		/// <summary>
		/// 查询枚举类型的属性列表
		/// </summary>
		/// <param name="EnumClassName">枚举名称</param>
		/// <returns></returns>
		public static List<EnumOption> GetEnumCells(string EnumClassName,string QuoteName= "Abp.Domain.Entities.Auditing")
		{
			List<EnumOption> enumOptions = new List<EnumOption>();
			Type classype = null;
			//根据类名获取Type对象
			//1.通过完全限定名
			string fullType = QuoteName + "." + EnumClassName;
			classype = Type.GetType(fullType);
            #region
            //2.如果上面的方式得不到，可以通过遍历程序集查找
            //得到所有程序集
            //Assembly[] assemblys = AppDomain.CurrentDomain.GetAssemblies();
            //Type[] types = null;
            //foreach (Assembly assembly in assemblys)
            //{
            //	//得到此程序集中所有类型
            //	types = assembly.GetTypes();
            //	if (types != null)
            //	{
            //		foreach (Type test in types)
            //		{
            //			//判断类型的名字是否与类名一致，忽视大小写
            //			if (test.Name.Equals(EnumClassName, StringComparison.CurrentCultureIgnoreCase))
            //			{
            //				classype = test;
            //				break;
            //			}
            //		}
            //	}
            //	if (classype != null)
            //	{
            //		break;
            //	}
            //}
            #endregion
            if (classype != null)
			{
                #region
                //属性
                //此接口只有类中的字段必须封装才能获得
                //var propertys = classype.GetProperties();
                //int i = 0;
                //foreach (var property in propertys)
                //{
                //	// 获取属性名
                //	var name = property.Name;
                //	var value = property.GetValue(classype, null);
                //	//enumOptions.Add(new  { Name = property.Name, TypeName = System.Convert.ChangeType(i, property.PropertyType) });
                //	// 给属性赋值
                //	//property.SetValue(Tclass, System.Convert.ChangeType(i, property.PropertyType), null);
                //	// 获取属性值
                //	//Debug.LogError(property.GetValue(Tclass, null));
                //}

                //方法
                //MethodInfo method = type.GetMethod("Add");
                //method.Invoke(object, null);
                #endregion
                //字段
                FieldInfo[] fieldInfos = classype.GetFields();
                foreach (FieldInfo fieldInfo in fieldInfos)
                {
                    DescriptionAttribute descAttr = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute)) as DescriptionAttribute;
                    if (descAttr != null)
                    {
						enumOptions.Add(new EnumOption()
						{
							typeName = fieldInfo.Name,
							typeDescription = descAttr.Description,
						});
					}
                    
                }
            }
			return enumOptions;
		}

		private static object GetEnumDescription<T>(object v)
		{
			throw new NotImplementedException();
		}

		public static string GetAbsoluteUri(HttpRequest request)
		{
			return new StringBuilder()
				.Append(request.Scheme)
				.Append("://")
				.Append(request.Host)
				.Append(request.PathBase)
				.Append(request.Path)
				.Append(request.QueryString)
				.ToString();
		}

		#region GMT时间转化
		/// <summary>  
		/// GMT时间转成本地时间  
		/// </summary>  
		/// <param name="gmt">字符串形式的GMT时间</param>  
		/// <returns></returns>  
		public static DateTime GMT2Local(string gmt)
		{
			DateTime dt = DateTime.MinValue;
			try
			{
				string pattern = "";
				if (gmt.IndexOf("+0") != -1)
				{
					gmt = gmt.Replace("GMT", "");
					pattern = "ddd, dd MMM yyyy HH':'mm':'ss zzz";
				}
				if (gmt.ToUpper().IndexOf("GMT") != -1)
				{
					pattern = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'";
				}
				if (pattern != "")
				{
					dt = DateTime.ParseExact(gmt, pattern, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal);
					dt = dt.ToLocalTime();
				}
				else
				{
					dt = Convert.ToDateTime(gmt);
				}
			}
			catch
			{
			}
			return dt;
		}
		/// <summary>  
		/// 本地时间转成GMT格式的时间  
		/// </summary>  
		public static string ToGMTFormat(DateTime dt)
		{
			return dt.ToString("r") + dt.ToString("zzz").Replace(":", "");
		}
		#endregion
	}
	/// <summary>
	/// 枚举类说明项
	/// </summary>
	public class EnumOption
	{
		/// <summary>
		/// 类型名称
		/// </summary>
		public string typeName { get; set; }
		/// <summary>
		/// 类型描述
		/// </summary>
		public string typeDescription { get; set; }
	}

}
